﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using LKVMLMADMIN.Filters;
using LKVMLMADMIN.Models;
using PagedList;
using System.Security.Cryptography;
using System.Text;
using LKVMLMLib;
using System.Globalization;
using LKVService;

namespace LKVMLMADMIN.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        public LKVService.User db = new LKVService.User();
        public int _userid { get; set; }           
        [AllowAnonymous]
        public ActionResult ChangePass()
        {
            if (Session["User"] != null)
            {
                ViewBag.Title = "Đổi mật khẩu";
                return View();
            }
            return RedirectToAction("Login", "Account");
        }           
        [HttpPost]
        [AllowAnonymous]
        public ActionResult ChangePass(LocalPasswordModel model)
        {
            try
            {             
                var current_u = (UserProfile)Session["User"];
                if(current_u==null)
                    return View();
                string oldPass = MD5Hash(model.OldPassword);
                var acc = db.chooseuser(current_u.UserId, oldPass);
                if (acc != null && model.ConfirmPassword == model.NewPassword)
                {
                    acc.Password = MD5Hash(model.ConfirmPassword);
                    acc.p = model.ConfirmPassword;
                    db.changPassword(acc);                  
                }
                else throw new Exception("Mật khẩu nhập không khớp");
            }
            catch (Exception ex)
            {
            }

            return RedirectToAction("Index", "Home");
        }   
        [AllowAnonymous]
        public ActionResult Userprofile()
        {
            ViewBag.Title = "Thông tin chi tiết";     
            if (Session["User"] != null)
            {
                var userDetail = Session["User"] as UserProfile;
                var model1 = new RegisterModel();
                DateTime NgaySinh = Convert.ToDateTime(userDetail.NGAYSINH);
                DateTime NgayCap = Convert.ToDateTime(userDetail.NGAYCAP);
                string a = NgaySinh.ToString("dd/MM/yyyy");
                string b = NgayCap.ToString("dd/MM/yyyy");
                model1.HoTen = userDetail.HOTEN;
                model1.UserName = userDetail.UserName;
                model1.GioiTinh = userDetail.GIOITINH;
                model1.NgaySinh = a;
                model1.NOISINH = userDetail.NOISINH;
                model1.DiaChi = userDetail.DIACHI;
                model1.MSTCANHAN = userDetail.MSTCANHAN;
                model1.NGAYCAP = b;
                model1.SoCMND = userDetail.SOCMND;
                model1.NOICAP = userDetail.NOICAP;
                model1.HoTenVoHoacChong = userDetail.HOTENVOHOACCHONG;
                model1.SoCMNDVOHOACCHONG = userDetail.SCMNDCUAVOHOACCHONG;
                model1.THANHPHO = userDetail.THANHPHO;
                model1.QUOCGIA = userDetail.QUOCGIA;
                model1.SDTNOILAMVIEC = userDetail.SDTNOILAMVIEC;
                model1.Email = userDetail.EMAIL;
                var configParent = db.getConfigTree();
                if (configParent.Option_1 == true)
                {
                    ViewBag.SysTree = "1";
                }
                if (configParent.Option_2 == true)
                {
                    ViewBag.BinaryTree = "2";
                }
                model1.GroupDrop = db.getListGroup().AsEnumerable().Select(x => new SelectListItem { Text = x.GroupName, Value = x.GroupID.ToString() }).ToList();

                if (userDetail.Parent_ID != 0 && userDetail.Parent_ID != null)
                {
                    int uidpr = Convert.ToInt32(userDetail.Parent_ID);
                    string usernameparent = db.findParent(uidpr).UserName;
                    model1.Name_IDParent = usernameparent;
                }
                if (userDetail.ParentB_ID != 0 && userDetail.ParentB_ID != null)
                {
                    int uidbnr = Convert.ToInt32(userDetail.ParentB_ID);
                    string usernamebinary = db.findParent(uidbnr).UserName;
                    model1.Name_IDBinary = usernamebinary;
                }            
                return View(model1);
            }
            else
                return RedirectToAction("Login", "Account");   
        }
        public static string MD5Hash(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));
            byte[] result = md5.Hash;
            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                strBuilder.Append(result[i].ToString("x2"));
            }
            return strBuilder.ToString();
        }
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            ViewBag.Title = "Đăng nhập hệ thống";

            //send pincode for admin
            return View();
        }
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Pincode()
        {
            //get account admin                
            var userAdmin = db.findUserByUserName("root");//db.getUserByGroup(3);
            if (userAdmin != null)
            {
                if (!db.CheckTimeLifePinCodeByEmail(userAdmin.EMAIL))
                {
                    string pinCode = LKVMLMADMIN.Common.StringHelper.RandomString(10);
                    string subject = "Pincode Request";
                    string ContentMail = string.Format("Pin Code for Administrator: {0}", pinCode);
                    var Author = new Authorized_Code();
                    Author.Code = pinCode;
                    Author.Createdate = DateTime.Now;
                    Author.During = 300;
                    Author.Email = userAdmin.EMAIL;
                    db.InsertPinCode(Author);
                    //send mail
                    LKVMLMADMIN.Common.MailHelper.SendMail(userAdmin.EMAIL, subject, ContentMail);
                }
            }
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Pincode(PincodeModel model)
        {
            var ExistCode = db.checkPinCode(model.PinCode);
            if (!ExistCode)
            {
                Session["User"] = (UserProfile)Session["tmpUser"];
                Session["key"] = "root";
                _userid = ((UserProfile)Session["User"]).UserId;
                return RedirectToAction("Dashboard", "Account");
            }
            else
            {
                ModelState.AddModelError("", "Pincode không tồn tại hay thời gian cấp pincode đã hết");
            }
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //change pass
                string a = Convert.ToString(model.Password);
                string b = MD5Hash(a);
                var user = db.getUser(model.UserName, b);

                if (user != null)
                {
                    if (user.GruopID == 3)
                    { 
                       Session["tmpUser"] = user;
                        return RedirectToAction("Pincode", "Account");
                    }else
                        ModelState.AddModelError("", "Not permission");
                }
                else
                {
                    ModelState.AddModelError("", "Mật khẩu sai thử lại.");
                }


            }
            return View(model);
        }
        [AllowAnonymous]
        public ActionResult Dashboard()
        {
            if (Session["User"] != null)
            {
                var user = Session["User"] as LKVMLMLib.UserProfile;
                var db = new LKVService.ProfitService();
                var AddfundStatisics = db.AddFundStatisics();
                ViewBag.AddFund = AddfundStatisics;
                var CashoutStatisics = db.CashoutStatisics();
                ViewBag.Caskhout = CashoutStatisics;
                var FeeThisWeek = db.FeeThisWeekStatisics();
                ViewBag.FeeThisWeek = FeeThisWeek;
                var checkWeek = db._GetThisWeekAndLastWeek(DateTime.Now);
                string err = "";
                if (checkWeek != null)
                {
                    // danh sach so lieu AddFund tu thu 2 den chu nhat cua tuan hien tai
                    var ListAddFundForThisWeek = db.AddFundForWeek(checkWeek.Item1);
                    ViewBag.ListAddFundThisWeek = ListAddFundForThisWeek;
                    // danh sach so lieu  Cashout tu thu 2 den chu nhat cua tuan hien tai
                    var ListCashoutForThisWeek = db.CashoutForWeek(checkWeek.Item1);
                    ViewBag.ListCahoutThisWeek = ListCashoutForThisWeek;
                    PerfectMoney c = new PerfectMoney();
                    var usersv = new LKVService.User();
                    // lay ra thang cask trong bang CashBankconfig
                    double SumUsedCashToday = 0;
                    double SumAmountCashUserYesterday = 0;
                    // tinh tien chuyen Cash trong ngay
                    double sumTodayReceived = 0;
                    double SumAmount_Yesterday_Received = 0;
                    double SumAmount_TotalWeekReceived = 0;
                    double SumAmount_ToTalWeekUsed = 0;
                    double SumAmount_ToFunfToday = 0;
                    double SumTotalFundReceived = 0;
                    double BlanceFerfect = 0;
                    double BlanceFund = 0;
                    ViewBag.Blance = 0;
                    //  var _chooseCash = usersv.LoadListCaskBankConfig().Where(w => w.Type == "cash" && w.UserId == user.UserId).FirstOrDefault();
                    var _chooseCash = usersv.LoadListCaskBankConfig().Where(w => w.Type == "cash").FirstOrDefault();
                    if (_chooseCash != null)
                    {
                        // tu thang nay truy van den tai khoan Perfectmoney cua no trong bang perfectmoney
                        var _SumAmountTodayCash = usersv.FindWalletHistoryByUserToDay(_chooseCash.UserId, null, DateTime.Now.Date);
                        if (_SumAmountTodayCash.Count() > 0)
                            sumTodayReceived =Convert.ToDouble( _SumAmountTodayCash.Sum(s => s.Amount));
                        //lay ngay hom qua
                        var _SumAmountYesterdayCash = usersv.FindWalletHistoryByUserToDay(_chooseCash.UserId, null, DateTime.Now.AddDays(-1));
                        if (_SumAmountYesterdayCash.Count() > 0)
                            SumAmount_Yesterday_Received = Convert.ToDouble(_SumAmountYesterdayCash.Sum(a => a.Amount));                      
                        //LAY TUAN NAY
                        var week = db._GetThisWeekAndLastWeek(DateTime.Now);
                        //lay so tien nhan trong tuan
                        var TotalweekAmount= usersv.getListWalletHistory().Where(w => w.CreateDate.Date >= week.Item1.Date && w.CreateDate.Date <= week.Item2.Date && w.UserId ==_chooseCash.UserId && w.WalletId==null);
                        if (TotalweekAmount.Count() > 0)
                            SumAmount_TotalWeekReceived =Convert.ToDouble( TotalweekAmount.Sum(S => S.Amount));
                        // lay so tien su dung trong tuan
                        var TotalAmountUsedtoWeek = usersv.getListWithdrawals().Where(w=>w.UserId ==_chooseCash.UserId && w.Create_Date.Value.Date>= week.Item1.Date && w.Create_Date.Value.Date <=week.Item2.Date && w.Status==1);
                        if (TotalAmountUsedtoWeek.Count() > 0)
                            SumAmount_ToTalWeekUsed =Convert.ToDouble( TotalAmountUsedtoWeek.Sum(s => s.Amout));                       
                        var _ChoosePefect = db.ChooosePerfectMoney(_chooseCash.UserId);
                        if (_ChoosePefect != null)
                        {
                            try
                            {
                                var BlanceCash = c.QueryBalance(_ChoosePefect.Account.ToString(), _ChoosePefect.Password);
                                if (BlanceCash.Count() > 0)
                                    BlanceFerfect = Convert.ToDouble(BlanceCash.Sum(s => double.Parse(s.Value, CultureInfo.InvariantCulture)));
                            }
                            catch(Exception ex)
                            {
                                BlanceFerfect = 0;
                               // err = "Login Perfect Money login failed ! Check IP your account";
                            }                           
                        }                    
                        ViewBag.Blance = BlanceFerfect;
                        // lay du lieu trong bang widrawal
                        // todayused
                        var _SumAmountUsed = usersv.FindWithdrawalByUser(_chooseCash.UserId,1,DateTime.Now,1);
                        if (_SumAmountUsed.Count() > 0)
                            SumUsedCashToday =Convert.ToDouble( _SumAmountUsed.Sum(s => s.Amout));
                        //yesterdayused
                        var _SumAmountYesterdayUsed = usersv.FindWithdrawalByUser(_chooseCash.UserId, 1, DateTime.Now.AddDays(-1), 1);
                        if (_SumAmountYesterdayUsed.Count() > 0)
                            SumAmountCashUserYesterday = Convert.ToDouble(_SumAmountYesterdayUsed.Sum(s => s.Amout));
                        //getListWithdrawals
                    }
                    // kiem tra coi user nay co phai thuoc giang Fund hay ko
                    var _chooseFund = usersv.LoadListCaskBankConfig().Where(w => w.Type == "fund").FirstOrDefault(); 
                    if (_chooseFund != null)
                    {
                        // TINH TOONG TIEN THEO FEFECT
                        var _ChooseFundPefect = db.ChooosePerfectMoney(_chooseFund.UserId);
                        if (_ChooseFundPefect != null)
                        {
                            try
                            {                                
                                var BlanceFund123 = c.QueryBalance(_ChooseFundPefect.Account.ToString(), _ChooseFundPefect.Password);                            
                                if (BlanceFund123.Count() > 0)
                                    BlanceFund = Convert.ToDouble(BlanceFund123.Sum(s => double.Parse(s.Value, CultureInfo.InvariantCulture)));
                            }
                            catch (Exception ex)
                            {
                                err = "Login Perfect Money login failed ! Check IP your account";
                                BlanceFund = 0;
                            }                          
                        }  
                        //SumAmount_ToFunfToday
                        // lay tong tien su dung trong ngay hom nay
                        var SumAmountTodayRecie = usersv.FindWalletHistoryByUserToDay(_chooseFund.UserId, null, DateTime.Now.Date);
                        if (SumAmountTodayRecie.Count() > 0)
                            SumAmount_ToFunfToday = Convert.ToDouble(SumAmountTodayRecie.Sum(s => s.Amount));
                        //lay tong tien tat ca cua thang fund
                        SumTotalFundReceived = usersv.SumTotalforUserInWalletHistory(_chooseFund.UserId,null);
                    }
                    // lay ra danh sach nhung thang sub trong danh sach user 
                    var _chooseListSub = usersv.findUsersByBankType("sub");
                  
                    var ListJonh = _chooseListSub.Select(s =>
                                    new LoadSubName
                                    {
                                        Name = s.UserName,
                                        Blance = usersv.SumTotalforUserInWalletHistory(s.UserId, null)
                                    });
                    ViewBag.ListSub = ListJonh.ToList();                 
                    ViewBag.CashTodayReceived = sumTodayReceived;
                    ViewBag.CashYesterday = SumAmount_Yesterday_Received;
                    ViewBag.UserUsedToday = CashoutStatisics.Item2;
                    ViewBag.UserUsedFerfectYesterday = CashoutStatisics.Item3;
                    ViewBag.SumAmountTotalWeekreceived = SumAmount_TotalWeekReceived;
                    ViewBag.SumAmountTotalWeekUsed = CashoutStatisics.Item4;
                    ViewBag.SumFundToday = SumAmount_ToFunfToday;
                    ViewBag.FundTotal = SumTotalFundReceived;
                    ViewBag.BlanFund = BlanceFund;
                }

                ViewBag.Err = err;
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public class LoadSubName
        {
            public string Name { get; set; }
            public double Blance { get; set; }
        }

    }
}
